package me.khrystal.store.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * usage: 列表 item 基类
 * author: kHRYSTAL
 * create time: 17/7/15
 * update time:
 * email: 723526676@qq.com
 */
public class RecyclerViewHolder extends RecyclerView.ViewHolder{

//    集合类 layout里包含的View 以view的Id作为key，view作为value
    protected SparseArray<View> mViews;
    protected Context mContext;

    public RecyclerViewHolder(Context context, View itemView) {
        super(itemView);
        mContext = context;
        mViews = new SparseArray<View>();
    }

    @SuppressWarnings("unchecked")
    private  <T extends View> T findViewById(int viewId){
        View view = mViews.get(viewId);
        if (view == null){
            view = itemView.findViewById(viewId);
            mViews.put(viewId,view);
        }
        //强制类型转换 因此要加unchecked
        return (T)view;
    }

    public View getView(int viewId){
        return findViewById(viewId);
    }

    public TextView getTextView(int viewId){
        return (TextView)getView(viewId);
    }

    public Button getButton(int viewId){
        return (Button)getView(viewId);
    }

    public ImageView getImageView(int viewId){
        return (ImageView)getView(viewId);
    }

    public ImageButton getImageButton(int viewId){
        return (ImageButton)getView(viewId);
    }

    public EditText getEditText(int viewId){
        return (EditText)getView(viewId);
    }

    public RecyclerViewHolder setText(int viewId, String value){
        TextView view  = findViewById(viewId);
        view.setText(value);
        return this;
    }

    public RecyclerViewHolder setBackground(int viewId, int resId){
        View view = findViewById(viewId);
        view.setBackgroundResource(resId);
        return this;
    }

    public RecyclerViewHolder setClickListener(int viewId, View.OnClickListener listener){
        View view = findViewById(viewId);
        view.setOnClickListener(listener);
        return this;
    }
}